package com.lvhx.java8;

import com.lvhx.base.Employee;
import com.lvhx.base.MyAgeCompare;
import com.lvhx.base.MyCompare;
import org.junit.Test;

import java.util.*;

public class LambdaTest {

    /**
     * 原来的匿名内部类
     */
    @Test
    public void test01(){
        Comparator<Integer> comparator = new Comparator<Integer>() {
            public int compare(Integer o1, Integer o2) {
                return o1.compareTo(o2);
            }
            @Override
            public boolean equals(Object obj) {
                return super.equals(obj);
            }
        };
        TreeSet<Integer> ts = new TreeSet<>(comparator);
        System.out.println(comparator.compare(1, 2));
    }

    /**
     * 现在的Lambda表达式
     */
    @Test
    public void test02(){
        Comparator<Integer> comparator = (a,b) -> Integer.compare(a,b);
        TreeSet<Integer> ts = new TreeSet<>(comparator);
    }

    /**
     * ------------------------------------------------------------------
     * 演变过程---依次递进
     * 需求，求年龄大于20的员工
     *
     */
    private List<Employee> employeeList = Arrays.asList(
            new Employee("A",10,100.0),
            new Employee("B",10,100.0),
            new Employee("C",10,100.0),
            new Employee("D",10,100.0));


    //方案一:直接写方法，每增加一个需求，就要增加一个方法
    public List<Employee> filterEmployee(List<Employee> employeeList){
        List<Employee> result = new ArrayList<>();
        for (Employee employee : employeeList) {
            if (employee.getAge() > 20){
                result.add(employee);
            }
        }
        return result;
    }

    //方案二：策略设计模式
    public List<Employee> comEmp(List<Employee> employeeList, MyCompare<Employee> com){
        List<Employee> result = new ArrayList<>();
        for (Employee employee : employeeList) {
            if (com.compare(employee)){
                result.add(employee);
            }
        }
        return result;
    }

    public void test3(){
        List<Employee> employees = comEmp(employeeList, new MyAgeCompare());
    }

    //方案三：匿名内部类
    public void test4(){
        List<Employee> employees = comEmp(employeeList, new MyCompare<Employee>() {
            @Override
            public boolean compare(Employee employee) {
                return employee.getAge() > 20;
            }
        });
    }

    //方案四：Lambda表达式
    public void test5(){
        List<Employee> employees = comEmp(employeeList,e -> e.getAge() > 20);
    }

    //方案五：Stream API
    public void test6(){
        employeeList.stream().filter(e -> e.getAge() > 20);
    }
}







































